package com.smart.village.big.screen.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.smart.village.big.screen.domain.NewsVo;
import com.smart.village.big.screen.mapper.ChangeAgricultureMapper;
import com.smart.village.big.screen.mapper.ChangeBenefitPeopleMapper;
import com.smart.village.big.screen.mapper.NewsMapper;
import com.smart.village.big.screen.service.ChangeBenefitPeopleService;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class ChangeBenefitPeopleServiceImpl implements ChangeBenefitPeopleService {
    @Autowired
    private ChangeBenefitPeopleMapper changeBenefitPeopleMapper;
    @Autowired
    private ChangeAgricultureMapper changeAgricultureMapper;
    @Autowired
    private NewsMapper newsMapper;

    @Override
    public List<JSONObject> getVillageTwoLeaderInfo(String townNumber, String villageNumber) {
        String[] townNumberArray = null;
        if (townNumber != null && !townNumber.isEmpty()) {
            townNumberArray = townNumber.split(",");
        }
        String[] villageNumberArray = null;
        if (villageNumber != null && !villageNumber.isEmpty()) {
            villageNumberArray = villageNumber.split(",");
        }

        return changeBenefitPeopleMapper.getVillageTwoLeaderInfo(townNumberArray, villageNumberArray);
    }

    @Override
    public JSONObject getVillagePeopleComplainInfo(String townNumber, String villageNumber) {
        List<JSONObject>  getVillagePeopleComplainInfoTop3 =    changeBenefitPeopleMapper.getVillagePeopleComplainInfoTop3(townNumber, villageNumber);
        List<JSONObject> getVillagePeopleComplainInfoBottomData = changeBenefitPeopleMapper.getVillagePeopleComplainInfoBottomData(townNumber, villageNumber);
        JSONObject donePercent = new JSONObject();
        BigDecimal total = new BigDecimal("0");
        BigDecimal done = new BigDecimal("0");
        for (JSONObject object : getVillagePeopleComplainInfoTop3) {
            if (object.getString("type").equals("总诉求")) {
                total = new BigDecimal(object.getString("cnt"));
            }
            if (object.getString("type").equals("已办结")) {
                done = new BigDecimal(object.getString("cnt"));
            }
        }
        if (total.compareTo(new BigDecimal("0")) == 0) {
            donePercent.put("cnt", "0");
        } else {
            donePercent.put("cnt", done.divide(total, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")).toString());
        }
        donePercent.put("type","办结率");
        getVillagePeopleComplainInfoTop3.add(donePercent);

        List<String> monthList = new ArrayList<>();
        List<String> totalList = new ArrayList<>();
        List<String> dealList = new ArrayList<>();

        for (JSONObject getVillagePeopleComplainInfoBottomDatum : getVillagePeopleComplainInfoBottomData) {
            monthList.add(getVillagePeopleComplainInfoBottomDatum.getString("month"));
            totalList.add(getVillagePeopleComplainInfoBottomDatum.getString("total"));
            dealList.add(getVillagePeopleComplainInfoBottomDatum.getString("deal"));
        }

        JSONObject btxxParams = new JSONObject();

        btxxParams.put("val1", totalList);
        btxxParams.put("val2", dealList);

        JSONObject legend1 = new JSONObject();
        legend1.put("code", "val1");
        legend1.put("name", "提交诉求");

        JSONObject legend2 = new JSONObject();
        legend2.put("code", "val2");
        legend2.put("name", "已解决诉求");

        JSONObject legend = new JSONObject();
        legend.put("legend1", legend1);
        legend.put("legend2", legend2);
        btxxParams.put("legend", legend);
        btxxParams.put("xData", monthList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("top3", getVillagePeopleComplainInfoTop3);
        jsonObject.put("btxxParams", btxxParams);
        return jsonObject;
    }

    @Override
    public JSONObject getVillagePeopleComplainHandleInfo(String townNumber, String villageNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = changeBenefitPeopleMapper.getVillagePeopleComplainHandleInfo(townNumber, villageNumber);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getVillageRegulationsAgreements(String townNumber, String villageNumber) {
        return ObjectUtils.isEmpty(changeBenefitPeopleMapper.getVillageRegulationsAgreements(townNumber,villageNumber))?new JSONObject():changeBenefitPeopleMapper.getVillageRegulationsAgreements(townNumber,villageNumber);

    }

    @Override
    public JSONObject getPolicyAdvocacy(int pageNum, int pageSize,String NewsTerminal) {
        PageHelper.startPage(pageNum, pageSize);
        List<String> treeList = Lists.newArrayList();
        treeList.add("NC0000000000071");
        List<NewsVo> newsVos = newsMapper.selectNewsVoListInCategorySerialNumberList(treeList, "","",0,NewsTerminal);
        PageInfo<NewsVo> pageInfo = new PageInfo<>(newsVos);
        execFormatSubTitle(newsVos);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("news", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getLawAdvocacy(int pageNum, int pageSize, String NewsTerminal) {
        PageHelper.startPage(pageNum, pageSize);
        List<String> treeList = Lists.newArrayList();
        treeList.add("NC0000000000081");
        List<NewsVo> newsVos = newsMapper.selectNewsVoListInCategorySerialNumberList(treeList, "","",0,NewsTerminal);
        PageInfo<NewsVo> pageInfo = new PageInfo<>(newsVos);
        execFormatSubTitle(newsVos);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("news", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getCenterThreeData(String townNumber, String villageNumber) {
        return changeBenefitPeopleMapper.getCenterThreeData(townNumber,villageNumber);
    }

    @Override
    public JSONObject getThreeAffairsDisclosureList(String townNumber, String villageNumber, String type, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> personalPointsAccountList = changeBenefitPeopleMapper.getThreeAffairsDisclosureList(townNumber, villageNumber,type);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(personalPointsAccountList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getThreeAffairsDisclosureDetail(String affairsSerialNumber) {
        JSONObject jsonObject = changeBenefitPeopleMapper.getThreeAffairsDisclosureDetail(affairsSerialNumber);
        jsonObject.put("Attachment_List", changeBenefitPeopleMapper.getThreeAffairsDisclosureDetailAttachmentList(affairsSerialNumber));
        return jsonObject;
    }

    @Override
    public JSONObject getThreeResourceInformationList(String townNumber, String villageNumber, String type, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> threeResourceInformationList = changeAgricultureMapper.getThreeResourceInformationList(townNumber, villageNumber,type);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(threeResourceInformationList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }


    @Override
    public JSONObject getListManagement(String listTypeSerialNumber, String townNumber, String villageNumber, String level, String search, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> listManagement = changeBenefitPeopleMapper.getListManagement(listTypeSerialNumber,townNumber,villageNumber,level,search);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(listManagement);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getListManagementDetail(String listManagementSerialNumber) {
        JSONObject jsonObject =  changeBenefitPeopleMapper.getListManagementDetail(listManagementSerialNumber);
        jsonObject.put("List_Material_List", changeBenefitPeopleMapper.getListMaterial(listManagementSerialNumber));
        jsonObject.put("List_Management_Attachment", changeBenefitPeopleMapper.getListManagementAttachment(listManagementSerialNumber));
        return jsonObject;
    }

    @Override
    public JSONObject getPersonalPointsAccountList(String townNumber, String villageNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> personalPointsAccountList = changeBenefitPeopleMapper.getPersonalPointsAccountList(townNumber, villageNumber);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(personalPointsAccountList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public List<JSONObject> getAllBluePlateTags(String tagSerialNumber) {
        return changeBenefitPeopleMapper.getAllBluePlateTags(tagSerialNumber);
    }

    @Override
    public JSONObject getServiceResourcesCoordsList(String townNumber, String villageNumber, String tagSerialNumber) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "FeatureCollection");
        JSONObject crs = new JSONObject();
        crs.put("type", "name");
        JSONObject crsP = new JSONObject();
        crsP.put("name", "EPSG:4490");
        crs.put("properties", crsP);

        jsonObject.put("crs", crs);
        List<JSONObject> list = changeBenefitPeopleMapper.getServiceResourcesCoordsList(townNumber, villageNumber, tagSerialNumber);
        List<JSONObject> features = Lists.newArrayList();
        for (JSONObject coords : list) {
            JSONObject feature = new JSONObject();
            feature.put("type", "Feature");
            feature.put("id", coords.getString("Shop_SerialNumber"));
            JSONObject geometry = new JSONObject();
            geometry.put("type", "point");
            geometry.put("coordinates", coords.getString("Coord").replace(" ", ""));
            feature.put("geometry", geometry);
            feature.put("properties", coords);
            if (!ObjectUtils.isEmpty(coords.getString("Coord")) && !coords.getString("Coord").replace(" ", "").equals("[]]")) {
                coords.remove("Coords");
                coords.remove("Coord");
                features.add(feature);
            }
        }
        jsonObject.put("features", features);
        return jsonObject;
    }

    @Override
    public List<JSONObject> getCropCategory() {
        return changeBenefitPeopleMapper.getCropCategory();
    }

    @Override
    public List<JSONObject> getCropCategoryMapDataList(String townNumber, String villageNumber, String cropCategorySerialNumber) {
        return changeBenefitPeopleMapper.getCropCategoryMapDataList(townNumber, villageNumber, cropCategorySerialNumber);
    }

    @Override
    public List<JSONObject> getNatureResourceType() {
        return changeBenefitPeopleMapper.getNatureResourceType();
    }

    @Override
    public List<JSONObject> getNatureResourceMapDataList(String townNumber, String villageNumber, String naturalResourceTypeSerialNumber) {
        return changeBenefitPeopleMapper.getNatureResourceMapDataList(townNumber, villageNumber, naturalResourceTypeSerialNumber);
    }

    @Override
    public List<JSONObject> getPolicyType() {
        return changeBenefitPeopleMapper.getPolicyType();
    }

    @Override
    public List<JSONObject> getPolicyTypeMapDataList(String townNumber, String villageNumber, String policyTypeSerialNumber) {
        return changeBenefitPeopleMapper.getPolicyTypeMapDataList(townNumber, villageNumber, policyTypeSerialNumber);
    }

    private void execFormatSubTitle(List<NewsVo> newsVoList) {
        newsVoList.forEach(newsVo -> {
            String newsSubTitle = newsVo.getNewsSubTitle();
            Document doc = Jsoup.parse(newsSubTitle);

            // 查找第一个<p>标签
            Elements paragraphs = doc.select("p");
            if (paragraphs.size() > 0) {
                Element firstParagraph = paragraphs.first(); // 获取第一个<p>标签
                String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                if (content.length() > 70) {
                    content = content.substring(0, 67) + "...";
                }
                newsVo.setNewsSubTitle(content);
                return;
            } else {
                Elements h1 = doc.select("h1");
                Elements h2 = doc.select("h2");
                Elements h3 = doc.select("h3");
                Elements h4 = doc.select("h4");
                Elements h5 = doc.select("h5");
                if (h1.size() > 0) {
                    Element firstParagraph = h1.first(); // 获取第一个<h1>标签
                    String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                    if (content.length() > 70) {
                        content = content.substring(0, 67) + "...";
                    }
                    newsVo.setNewsSubTitle(content);
                    return;
                }
                if (h2.size() > 0) {
                    Element firstParagraph = h2.first(); // 获取第一个<h2>标签
                    String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                    if (content.length() > 70) {
                        content = content.substring(0, 67) + "...";
                    }
                    newsVo.setNewsSubTitle(content);
                    return;
                }
                if (h3.size() > 0) {
                    Element firstParagraph = h3.first(); // 获取第一个<h1>标签
                    String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                    if (content.length() > 70) {
                        content = content.substring(0, 67) + "...";
                    }
                    newsVo.setNewsSubTitle(content);
                    return;
                }
                if (h4.size() > 0) {
                    Element firstParagraph = h4.first(); // 获取第一个<h1>标签
                    String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                    if (content.length() > 70) {
                        content = content.substring(0, 67) + "...";
                    }
                    newsVo.setNewsSubTitle(content);
                    return;
                }
                if (h5.size() > 0) {
                    Element firstParagraph = h5.first(); // 获取第一个<h1>标签
                    String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                    if (content.length() > 70) {
                        content = content.substring(0, 67) + "...";
                    }
                    newsVo.setNewsSubTitle(content);
                    return;
                }
            }
        });
    }
}
